<?php
/**
 * 商品云组件分类Model
 * @file 	CategoryModel.class.php
 * @author 	kelecode@gmail.com
 * @date 	2013-06-15
 * modify
 */
class CategoryModel extends Model{

	private $table;
	public $pageSize;

	public function __construct(){
		parent::__construct();

		$this->table = C('db_table_prefix').'items_categories';
		$this->pageSize = C('page.page_size');
	}
	
	/**
	 * 分类列表
	 */
	public function categoriyList($sub=true){
		$categories =  $this->getCategories();
		$items = array();
		$lists = array();
		foreach($categories['lists'] as $key => $val){
			$pid = $val['parent_id'];
			$id = $val['id'];
			if($pid == 0){
				$items[$id] = $val;
				$items[$id]['sub'] = array();
			}else{
				$items[$pid]['sub'][] = $val;
			}
		}		
		foreach($items as $category){
			$sublist = $category['sub'];
			unset($category['sub']);
			$lists[] = $category;
			if( is_array($sublist) && !empty($sublist) ){
				foreach($sublist as $sub){
					$lists[] = $sub;
				}
			}
		}
		
		return $lists;
	}

	/**
	 * 获取分类信息
	 * @param array $arg 若指定id 则取音条数据，若指定pid则取该parent_id下的数据，若不指定任何参数则取所有数据。
	 * @return array
	 */
	public function getCategories( $arg=array('id'=>null,'pid'=>null) ){
		$pageSize = $this->pageSize;
		$currentPage = (int)$_GET[C('page.var_page')];
		$currentPage = $currentPage <= 0 ? 1 : $currentPage;
		$start = ($currentPage - 1) * $pageSize;
        $start = $start < 0 ? 0 : $start;

		$lists = array();
		$sql = "SELECT count(*) AS count FROM `{$this->table}` WHERE `id`>0";
		if( isset($arg['id']) ){
			$id = (int)$arg['id'];
			$sql .= " AND `id`='{$id}'";
		}
		if( isset($arg['pid']) ){
			$pid = (int)$arg['pid'];		
			$sql .= " AND `parent_id`='{$pid}'";
		}
		$count = $this->query($sql);
        $count = $count[0]['count'];
		$sql = str_replace('count(*) AS count','*',$sql);
        $sql .= " ORDER BY `parent_id` ASC, `status` DESC,`sort` ASC,`id` ASC LIMIT {$start},{$pageSize}";
		$lists = $this->query($sql);
		
		return array('count' => $count,'lists' => $lists);
	}
	
	/**
	 * 获取指定级别的分类信息
	 */
	public function getCategoryByPid($pid){
		$pid = (int)$pid;
		$category = $this->getCategories( array('pid'=>$pid) );

		return $category['lists'];
	}

	/**
	 * 获取单条分类信息
	 */
	public function getCategoryById($id){
		if(empty($id)){
			return false;
		}
		$category = $this->getCategories( array('id'=>$id) );

		return $category['lists'][0];
	}

	/**
	 * 添加分类
	 */
	public function addCategory($data){
		$time = time();
		$data['sort'] = is_null($data['sort']) ? 99 : $data['sort'];
		$data['status'] = is_null($data['status']) ? 1 : $data['status'];
		$sql = "INSERT INTO `{$this->table}`
			(`parent_id`, `name`,`description`,`sort`,`ctime`,`utime`,`status`)
			VALUES ('{$data['parent_id']}', '{$data['name']}','{$data['description']}','{$data['sort']}','{$time}','{$time}','{$data['status']}')";
		$result = $this->execute($sql);

		return $result;
	}

	/**
	 * 编辑分类
	 * @param array $data array('id'=>'','name'=>'','desc'=>''...)
	 * @return boolean true or false
	 */
	public function editCategory($data){
		if(empty($data['id'])){
			return false;
		}
		$data['sort'] = is_null($data['sort']) ? 99 : $data['sort'];
		$data['status'] = is_null($data['status']) ? 1 : $data['status'];
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET `parent_id`='{$data['parent_id']}', `name`='{$data['name']}',`description`='{$data['description']}',`sort`='{$data['sort']}',`utime`='{$utime}',`status`='{$data['status']}' WHERE `id`='{$data['id']}' LIMIT 1";
		$result = $this->execute($sql);

		return $result;
	}

	/**
	 * 删除分类(若当前删除的分类为一级分类，则同时删除对应的二级分类)
	 * @param int $id
	 * @return boolean true or false
	 */
	public function delCategory($id){
		if(empty($id)){
			return false;
		}
		$sql = "UPDATE `{$this->table}` SET `status`='0' WHERE `id`='{$id}' AND `parent_id` = '{$id}'";
		$result = $this->execute($sql);

		return $result;
	}

	/**
	 * 更新状态
	 */
	public function updateStatus($ids, $status){
		if(!is_array($ids) || empty($ids)){
			return false;
		}
		$ids = implode(',',$ids);
		$status = !in_array($status,array(0,1)) ? 1 : $status;
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET `status`='{$status}', `utime`='{$utime}' WHERE `id` in ({$ids})";
		$result = $this->execute($sql);

		return $result;
	}

	/**
	 * 更新排序
	 */
	public function updateSort($id, $num){
		if( empty($id) ){
			return false;
		}
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET `sort`='{$num}', `utime`='{$utime}' WHERE `id`='{$id}' LIMIT 1";
		$result = $this->execute($sql);
		
		return $result;
	}

}